<?php

namespace app\controller\api\info;


use app\BaseController;
use app\common\repositories\info\ArticleRecordRepository;
use app\common\repositories\info\ArticleRepository as repository;
use think\App;
use think\exception\ValidateException;

class Article extends BaseController
{
    protected $repository;

    public function __construct(App $app, repository $repository)
    {
        parent::__construct($app);
        $this->repository = $repository;
    }


    public function detail($id)
    {
        $user = request()->userInfo();

        $content = $this->repository->get($id);
        if(!$content)
            throw new ValidateException('数据不存在');

        if(!$user->member && !$user->course_memebr){
            throw new ValidateException('请开通课程会员');
        }

        if($content->is_del){
            throw new ValidateException('内容已下架');
        }


        $this->repository->incrNumberField($id,'views');

        $record = app()->make(ArticleRecordRepository::class)->getWhere([
            'article_id'=>$id,
            'uid'=>$user->uid,
        ]);

        if($record){
            $record->save(['update_time'=>date('Y-m-d H:i:s')]);
        }else{
            app()->make(ArticleRecordRepository::class)->create([
                'article_id'=>$id,
                'uid'=>$user->uid,
            ]);
        }

        return success($content);
    }


    public function userLst()
    {

        [$page,$limit] = $this->request->page();
        $count = app()->make(ArticleRecordRepository::class)->getSearch()->where('uid',request()->uid())->count();
        $list = app()->make(ArticleRecordRepository::class)->getSearch()->page($page,$limit)->with(['article'])->where('uid',request()->uid())->order('create_time desc')->select();

        return success(compact('count','list'));
    }



    public function lst()
    {
        [$page,$limit] = $this->request->page();
        $count = $this->repository->getSearch()->where('is_del',0)->count();
        $list = $this->repository->getSearch()->order('id desc')->where('is_del',0)->page($page,$limit)->select();
        return success(compact('count','list'));
    }
}